package com.hula.onion.book.server.spider.platforms.xinlianzaixian;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by work on 2018/1/25.
 */
@Component
public class NewUnionSpiderHelper {
    private static final Logger logger = LoggerFactory.getLogger(NewUnionSpiderHelper.class);

    /**
     * 组装请求参数
     *
     * @param form
     * @return
     */
    public Map<String, Object> installRequestParams(LoginForm form) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("paramMap.pageId", "userlogin");
        map.put("paramMap.email", form.getUserName());
        map.put("paramMap.password", form.getPassword());
        map.put("paramMap.afterLoginUrl", "https://www.newunion.cn/login.do");
        return map;
    }

    /**
     * 解析账户余额
     *
     * @param html
     * @return
     */
    public CommonResponse parseAccountBalance(String html) {
        if (StringUtils.isEmpty(html)) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
        try {
            Document doc = Jsoup.parse(html);
            Element el = doc.select("a.accountSum").first();
            String amount = StringUtils.remove(el.text(), "元");
            Element wIEl = doc.selectFirst("label.forPayInterest");
            String waitIntrest = wIEl.text();
            Element tIEl = doc.selectFirst("div.homeAmount-fl");
            String totalIntrest = tIEl.getAllElements().get(2).text();
            AccountInfo accountInfo = new AccountInfo();
            accountInfo.setAmount(new BigDecimal(amount));
            accountInfo.setWaitIntrest(new BigDecimal(waitIntrest));
            accountInfo.setTotalIntrest(new BigDecimal(StringUtils.remove(totalIntrest, "元")));
            return new CommonResponse(accountInfo);
        } catch (Exception e) {
            logger.error("[NewUnionSpiderHelper] parseAccountBalance fail!", e);
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
    }
}
